package com.topboya.linker.ui.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.suke.widget.SwitchButton;
import com.topboya.linker.AppConst;
import com.topboya.linker.R;
import com.topboya.linker.model.levelitem.FollowUserGroup;
import com.topboya.linker.model.levelitem.SelectDeviceGroup;
import com.topboya.linker.model.levelitem.SelectProductGroup;
import com.topboya.linker.model.levelitem.SelectVistorItem;
import com.topboya.linker.model.response.CustomerByOrgIdResponse;
import com.topboya.linker.model.response.OrganizationResopnse;
import com.topboya.linker.model.response.ProductInforListReponse;
import com.topboya.linker.model.response.SelectFileResponse;
import com.topboya.linker.model.response.VisitTypeResponse;
import com.topboya.linker.model.save.VisitCustomerBean;
import com.topboya.linker.ui.adapter.VisitypeAdapter;
import com.topboya.linker.ui.base.activity.BaseActivity;
import com.topboya.linker.ui.presenter.CreateTaskPrensenter;
import com.topboya.linker.ui.view.CreateTaskView;
import com.topboya.linker.utils.AndroidUtils;
import com.topboya.linker.utils.LogUtils;
import com.topboya.linker.utils.UIUtils;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class xCreateTaskActivity extends BaseActivity<CreateTaskView,CreateTaskPrensenter> implements CreateTaskView {
    private static final String TAG = "xCreateTaskActivity";
    private Toolbar toolbar;
    private TextView toolbar_title;
    private TextView tv_toolbar_right;
    private RelativeLayout rl_select_device;
    private RelativeLayout rl_visitlist;
    private RecyclerView rl_visittype;
    private TextView tv_sustomer_name;
    private TextView tv_visit_name;
    private View view_line;
    private SwitchButton switch_view;
    private TextView tv_start_time_day;
    private TextView tv_start_time_hour;
    private TextView tv_end_time_day;
    private TextView tv_end_time_hour;
    private TextView tv_product;
    private TextView tv_file;
    private LinearLayout ll_start_time;
    private LinearLayout ll_end_time;
    private LinearLayout ll_full;
    private LinearLayout ll_select_time;
    private TextView tv_full_startime;
    private TextView tv_full_endtime;
    private TextView tv_follow_usr_name;
    private RelativeLayout rl_select_product;
    private RelativeLayout rl_select_followuser;
    private EditText et_task_describle;
    private SelectDeviceGroup docDetailInfo;
    private List<SelectVistorItem> departmentListselected;
    private VisitypeAdapter visitypeAdapter;
    private ArrayList<SelectProductGroup> productDetailInfoList;
    private ArrayList<SelectFileResponse.FileList> selectFileList;
    private ArrayList<FollowUserGroup> selectfollowuser;


    @Override
    protected int getLayoutId() {

        return R.layout.xactivity_create_task;
    }

    @Override
    protected void initView() {
        toolbar = findViewById(R.id.toolbar);
        toolbar_title = findViewById(R.id.toolbar_title);
        tv_toolbar_right = findViewById(R.id.tv_toolbar_right);
        rl_select_device  = findViewById(R.id.rl_select_device);
        rl_visitlist  = findViewById(R.id.rl_visitlist);
        tv_sustomer_name = findViewById(R.id.tv_sustomer_name);
        tv_visit_name = findViewById(R.id.tv_visit_name);
        view_line = findViewById(R.id.view_line);
        rl_visittype = findViewById(R.id.rl_visittype);
        switch_view = findViewById(R.id.switch_button);
        tv_start_time_day = findViewById(R.id.tv_start_time_day);
        tv_start_time_hour = findViewById(R.id.tv_start_time_hour);
        tv_end_time_day = findViewById(R.id.tv_end_time_day);
        tv_end_time_hour = findViewById(R.id.tv_end_time_hour);
        ll_start_time = findViewById(R.id.ll_start_time);
        ll_end_time = findViewById(R.id.ll_end_time);
        ll_full = findViewById(R.id.ll_full);
        ll_select_time = findViewById(R.id.ll_select_time);
        rl_select_followuser = findViewById(R.id.rl_select_followuser);
        rl_select_product = findViewById(R.id.rl_select_product);
        tv_product = findViewById(R.id.tv_product);
        tv_file = findViewById(R.id.tv_file);
        tv_full_startime = findViewById(R.id.tv_full_startime);
        tv_full_endtime = findViewById(R.id.tv_full_endtime);
        tv_follow_usr_name = findViewById(R.id.tv_follow_usr_name);
        et_task_describle = findViewById(R.id.et_task_describle);
    }

    @Override
    protected void onNewIntent(Intent intent) {

        LogUtils.v(TAG + "--onNewIntent()");
//        super.onNewIntent(intent);
        boolean isDoc = intent.getBooleanExtra("isDoc",true);
        LogUtils.v(TAG + "--isDoc()"+isDoc);

        if (isDoc){

            getDeviceAndDoceInfo(intent);

        }else {

            getProductAndFileInfo(intent);
        }

    }

    private void getProductAndFileInfo(Intent intent) {

        productDetailInfoList = (ArrayList<SelectProductGroup>) intent.getSerializableExtra("productDetailInfoLists");
        for(Map.Entry<String,  SelectFileResponse.FileList> entry : AppConst.FILE_SELECTED_MAP.entrySet()) {

            SelectFileResponse.FileList fileList = entry.getValue();
            if (null != fileList){

                selectFileList.add(fileList);
            }
        }
        if (productDetailInfoList.size() ==1 && null ==selectFileList){

            tv_product.setText(productDetailInfoList.get(0).getProductName());
            tv_product.setCompoundDrawables(null,null,null,null);
            tv_file.setVisibility(View.GONE);

        }else {

            tv_product.setText(String.valueOf(productDetailInfoList.size()));
            Drawable drawable = getResources().getDrawable(R.drawable.produce_gree);
            drawable.setBounds(0,0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_product.setCompoundDrawables(drawable,null,null,null);

            tv_file.setText(String.valueOf(selectFileList.size()));
            Drawable drawablefile = getResources().getDrawable(R.drawable.data);
            drawable.setBounds(0,0, drawablefile.getMinimumWidth(), drawablefile.getMinimumHeight());
        }
    }

    private void getDeviceAndDoceInfo(Intent intent) {

        docDetailInfo = (SelectDeviceGroup) intent.getSerializableExtra("DocDetailInfo");
        departmentListselected = (List<SelectVistorItem>) intent.getSerializableExtra("departmentListselected");
        if (null ==docDetailInfo){
            tv_sustomer_name.setText("选择终端");
        }else {
            tv_sustomer_name.setText(docDetailInfo.getOrgName());
        }
        if (null==departmentListselected ||departmentListselected.size() ==0){
            LogUtils.v(TAG + "departmentListselected==null");

            rl_visitlist.setVisibility(View.GONE);
            view_line.setVisibility(View.GONE);
        }else {
            String namelist="";
            for (SelectVistorItem departmentList: departmentListselected){

                namelist = departmentList.getCusName()+","+namelist;
            }
            namelist = namelist.substring(0,namelist.length() -1);
            LogUtils.v(TAG + "namelist:"+namelist);
            rl_visitlist.setVisibility(View.VISIBLE);
            view_line.setVisibility(View.VISIBLE);
            tv_visit_name.setText(namelist);
        }
    }

    @Override
    protected void initData() {

        toolbar_title.setText("新建拜访");
        startime = AndroidUtils.getCurrentTimeSH();
        endtime = AndroidUtils.getCurrentTimeSHOfoneHoursLate();
        String timeday=  AndroidUtils.getCurrentTimeDay();
        tv_start_time_day.setText(timeday);
        String timehour = AndroidUtils.getCurrentTimeHours();
        tv_start_time_hour.setText(timehour);
        String timedaylate = AndroidUtils.getCurrentTimeDayLate();
        tv_end_time_day.setText(timedaylate);
        String timehourlate = AndroidUtils.getCurrentTimeHoursLate();
        tv_end_time_hour.setText(timehourlate);
        tv_full_startime.setText(AndroidUtils.getCurrentTimeDay());
        tv_full_endtime.setText(AndroidUtils.getCurrentTimeDayLate());
//        获取学术类型
        mPresenter.getVisitType();
//        当选取拜访对象后，得到的数据；
//        用来保存选中文件对象
        selectFileList = new ArrayList<>();
    }


    @Override
    protected void initListener() {

        rl_select_device.setOnClickListener(v -> {

            jumpToActivity(SelectDeviceActivity.class);


        });
        rl_visitlist.setOnClickListener(v -> {
                //查看已选择的拜访对象
             Intent intent = new Intent(xCreateTaskActivity.this,SelectedDepartListActivity.class);
             intent.putExtra("departmentListselected", (Serializable) departmentListselected);
//             在查案拜访对象的时候将终端纤细传递到查看页面，然后在传递回来，不然，本页面创建任务的时候为空
             intent.putExtra("DocDetailInfo",docDetailInfo);
             startActivity(intent);
        });

        switch_view.setOnCheckedChangeListener((view, isChecked) ->{

            LogUtils.v(TAG + "isChecked: "+isChecked);
            if (isChecked){
//                表示全天
               ll_select_time.setVisibility(View.GONE);
               ll_full.setVisibility(View.VISIBLE);

            }else {

//                表示非全天
                ll_select_time.setVisibility(View.VISIBLE);
                ll_full.setVisibility(View.GONE);
            }

        });

        ll_start_time.setOnClickListener(v -> startimeClick());
        ll_end_time.setOnClickListener(v -> endtimeClick());
        tv_full_startime.setOnClickListener(v -> { startTimeFullClick();});
        tv_full_endtime.setOnClickListener(v -> { endtimeFullClick(); });

        rl_select_product.setOnClickListener(v -> {

//            jumpToActivity(SellectProductInforActivity.class);
            Intent intent = new Intent(xCreateTaskActivity.this,SellectProductInforActivity.class);
            intent.putExtra("productDetailInfoList",productDetailInfoList);
            startActivityForResult(intent,1001);

        });
        rl_select_followuser.setOnClickListener(v -> {
            //跳转到选择随访人界面
//            jumpToActivity(FollowUserActivity.class);
            Intent intent = new Intent(xCreateTaskActivity.this,FollowUserActivity.class);
            intent.putExtra("selectfollowuser",selectfollowuser);
            startActivityForResult(intent,1002);

        });

        tv_toolbar_right.setOnClickListener(v -> {
//            创建任务
            if (null ==docDetailInfo){

                UIUtils.showToast("请先选择终端信息");
                return;
            }
             String orgID = docDetailInfo.getId();
             String orgName = docDetailInfo.getOrgName();
             String createDate = "";
             String timeUse = "";
             String startTime = startime;
             String endTime = endtime;
            if (null ==productDetailInfoList || productDetailInfoList.size() ==0){

                UIUtils.showToast("请先选择产品");
                return;
            }
            ArrayList<VisitTypeResponse.Data> selectedVisitptelist = visitypeAdapter.getSelectedItem();
            if (null== selectedVisitptelist || selectedVisitptelist.size()==0){
                UIUtils.showToast("请先选择类型");
                return ;
            }
             String cusList = getCusList();
             String followName="";
             String followId = "";
             String remarks = et_task_describle.getText().toString().trim();
             if (null !=selectfollowuser && selectfollowuser.size() >0){

                 for (int i=0;i < selectfollowuser.size();i++){

                     followName =selectfollowuser.get(i).getName()+","+followName;
                     followId =selectfollowuser.get(i).getId()+","+followId;
                 }
                 followName =followName.substring(0, followName.length()-1);
                 followId =followId.substring(0, followId.length()-1);

             }

            LogUtils.v(TAG + "orgID:"+orgID);
            LogUtils.v(TAG + "orgName:"+orgName);
            LogUtils.v(TAG + "createDate:"+createDate);
            LogUtils.v(TAG + "startTime:"+startTime);
            LogUtils.v(TAG + "endTime:"+endTime);
            LogUtils.v(TAG + "cusList:"+cusList);
            LogUtils.v(TAG + "followName:"+followName);
            LogUtils.v(TAG + "followId:"+followId);
            LogUtils.v(TAG + "remarks:"+remarks);


             mPresenter.createTaskSuccess(orgID,orgName,createDate,timeUse,startTime,endTime,cusList,followName,followId,remarks,"M");

        });
        toolbar.setNavigationOnClickListener(v -> {

            setResult(1002);
            finish();

        });
    }

    private String getCusList() {

        VisitCustomerBean visitCustomerBean  = new VisitCustomerBean();
        List<VisitCustomerBean.CusList> cusLists = new ArrayList<>();
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        String visitypeid ="";
        String filesId ="";
         int filesize =0;
         String productIds="";
        ArrayList<VisitTypeResponse.Data> selectedVisitptelist = visitypeAdapter.getSelectedItem();

        for (VisitTypeResponse.Data selectedVisitpte: selectedVisitptelist){

            visitypeid = selectedVisitpte.getValue()+","+visitypeid;
        }
         visitypeid = visitypeid.substring(0, visitypeid.length() - 1);
        if (null != selectFileList &&selectFileList.size() >0) {

            for (int j = 0; j < selectFileList.size(); j++) {

               filesize = selectFileList.size();
               filesId = selectFileList.get(j).getId()+","+filesId ;

            }
             filesId = filesId.substring(0, filesId.length() - 1);
        }

        for (int j=0;j <productDetailInfoList.size();j++){

            productIds = productDetailInfoList.get(j).getId()+","+productIds;
        }
        productIds =productIds.substring(0, productIds.length()-1);

        for (SelectVistorItem  departmentList:departmentListselected){

            VisitCustomerBean.CusList cusList = visitCustomerBean.new CusList();
            cusList.setCusId(departmentList.getId());
            cusList.setCusName(departmentList.getCusName());
            cusList.setVisitType(visitypeid);
            cusList.setFileNum(String.valueOf(filesize));
            cusList.setFilesId(filesId);
            cusList.setProductIds(productIds);
            cusList.setSwfwType("");
            cusLists.add(cusList);
        }
        String cusListString = gson.toJson(cusLists);

        LogUtils.v(TAG + "cusListString:"+cusListString);
        return cusListString;
    }


    @Override
    protected CreateTaskPrensenter createPresenter() {

        return new CreateTaskPrensenter(this);

    }

//    创建任务成功
    @Override
    public void createTaskSuccess() {

        UIUtils.showToast("创建任务成功");

        jumpToActivity(xMainActivity.class);

    }

//    获取学术类型
    @Override
    public void getVisitType(List<VisitTypeResponse.Data> visitTypeResponses) {

        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
//        rl_visittype.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, 2, 0xBFC0C2));
        rl_visittype.setLayoutManager(manager);
        visitypeAdapter = new VisitypeAdapter(this,(ArrayList<VisitTypeResponse.Data>) visitTypeResponses);
        rl_visittype.setAdapter(visitypeAdapter);
    }

    private String startime;

    private void startimeClick() {

        TimePickerView pvTime = new TimePickerBuilder(this, (date, v1) -> {

              startime = AndroidUtils.getSelectTime(date);
              tv_start_time_day.setText(AndroidUtils.getSelectDayTime(date));
              tv_start_time_hour.setText(AndroidUtils.getSelectHoursTime(date));
        })      .setType(new boolean[]{true, true, true, true, true, false})
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setLabel("","","","","","")
                .build();
        pvTime.show();
    }

  private String endtime;

    private void endtimeClick() {

        TimePickerView pvTime = new TimePickerBuilder(this, (date, v1) -> {

            endtime = AndroidUtils.getSelectTime(date);
            tv_end_time_day.setText(AndroidUtils.getSelectDayTime(date));
            tv_end_time_hour.setText(AndroidUtils.getSelectHoursTime(date));
        })      .setType(new boolean[]{true, true, true, true, true, false})
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setLabel("","","","","","")
                .build();
        pvTime.show();
    }


    private void endtimeFullClick() {

        TimePickerView pvTime = new TimePickerBuilder(this, (date, v1) -> {

            endtime = AndroidUtils.getSelectFullTime(date)+" 23:59";

            LogUtils.v(TAG + "endtime:"+endtime);
            tv_end_time_day.setText(AndroidUtils.getSelectDayTime(date));
            tv_end_time_hour.setText(AndroidUtils.getSelectHoursTime(date));
        })      .setType(new boolean[]{true, true, true, false, false, false})
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setLabel("","","","","","")
                .build();
        pvTime.show();

    }

    private void startTimeFullClick() {

        TimePickerView pvTime = new TimePickerBuilder(this, (date, v1) -> {

            endtime = AndroidUtils.getSelectFullTime(date)+" 00:00";
            tv_end_time_day.setText(AndroidUtils.getSelectDayTime(date));
            tv_end_time_hour.setText(AndroidUtils.getSelectHoursTime(date));
        })      .setType(new boolean[]{true, true, true, false, false, false})
                .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                .isCyclic(true)//是否循环滚动
                .setLabel("","","","","","")
                .build();
        pvTime.show();


    }



    //获取最终时间，这个应该修改时间选择器源码，这样做不是很好
    private String getLastTime(Date date) {

        String time[] = getTime(date).split(":");
        String secondes = String .valueOf(Integer.parseInt(time[1] )*10);
        String time1 = time[0] + ":"+secondes+":00";
        return time1;
    }

    private String getTime(Date date) {
        //可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return format.format(date);
    }
    //  初始化已经被选择的数据


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // 表示选择的只是选择了产品
        if (resultCode ==1002){

            productDetailInfoList = (ArrayList<SelectProductGroup>) data.getSerializableExtra("productDetailInfoList");
            LogUtils.v(TAG + "productDetailInfoList:"+productDetailInfoList.toString());
            setProductAndFile();

        }
//        这里返回的是随访人的信息
        if (resultCode ==1003){

            selectfollowuser = (ArrayList<FollowUserGroup>) data.getSerializableExtra("selectfollowuser");
            LogUtils.v(TAG + "selectfollowuser:"+selectfollowuser.toString());
            String followuserlist="";
            for (FollowUserGroup followUserGroup: selectfollowuser){

                followuserlist = followUserGroup.getName()+","+followuserlist;
            }
            followuserlist = followuserlist.substring(0,followuserlist.length() -1);
            LogUtils.v(TAG + "namelist:"+followuserlist);
            tv_follow_usr_name.setText(followuserlist);
        }

    }

    private void setProductAndFile() {
        selectFileList.clear();
        for(Map.Entry<String,  SelectFileResponse.FileList> entry : AppConst.FILE_SELECTED_MAP.entrySet()) {

            SelectFileResponse.FileList fileList = entry.getValue();
            if (null != fileList){

                selectFileList.add(fileList);
            }
        }
        LogUtils.v(TAG + "selectFileList:"+selectFileList.size());
        if (productDetailInfoList.size() ==1 && (null ==selectFileList ||selectFileList.size() ==0)){

            tv_product.setText(productDetailInfoList.get(0).getProductName());
            tv_product.setCompoundDrawables(null,null,null,null);
            tv_file.setVisibility(View.GONE);

        }else {

            tv_product.setText(String.valueOf(productDetailInfoList.size()));
            Drawable drawable = getResources().getDrawable(R.drawable.produce_gree);
            drawable.setBounds(0,0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tv_product.setCompoundDrawables(drawable,null,null,null);
            if (null !=selectFileList &&selectFileList.size() >0){

                tv_file.setVisibility(View.VISIBLE);
                tv_file.setText(String.valueOf(selectFileList.size()));
                Drawable drawablefile = getResources().getDrawable(R.drawable.data);
                drawable.setBounds(0,0, drawablefile.getMinimumWidth(), drawablefile.getMinimumHeight());
            }

        }

    }


    @Override
    public void onBackPressed() {

          back();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 是否触发按键为back键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        } else { // 如果不是back键正常响应
            return super.onKeyDown(keyCode, event);
        }
    }

    private void back() {

      //从创建任务页面只写返回到主页
       setResult(1002);
       finish();
    }
}
